<?php


namespace app\ymsh\controller\java;


use app\common\service\finance\merchant\WithdrawService;
use app\common\service\finance\merchant\WithdrawSuccessService;
use app\model\AgentMerchantStat;
use app\model\AgentMerchantWithdraw;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class Withdraw extends BaseController
{

    /**
     * 发起提现
     * @return \think\response\Json
     */
    public function create()
    {


        //加锁，中间件
        $params = request()->all();

        if ($msg = dmjValidate([
            'ids' => 'require',
            'merchant_id' => 'require',
            'type' => 'require',
            'alipay' => 'requireIf:type,1',
            'bank_card_no' => 'requireIf:type,2|require',
            'bank_username' => 'requireIf:type,2|require',
            'bank_name' => 'requireIf:type,2|require',
        ], [], $params)) return fail($msg);


        $cacheKey = serialize($params);
        if (cache($cacheKey)) return fail('正在处理');
        cache($cacheKey, 1, 20);


        try {

            $res = (new WithdrawService())->submit($params);

            cache($cacheKey, null);

        } catch (Exception $exception) {

            cache($cacheKey, null);
            return fail($exception->getMessage());

        }
        return !empty($res) ? success('', $res) : fail();
    }

    /**
     * 已通过
     */
    public function pass(){


        return success('操作成功', []);

        //加锁，中间件
        $params = request()->all();

        if ($msg = dmjValidate(['id' => 'require', ], [], $params)) return fail($msg);

        $id = $params['id'] ?? 0;

        try {

            Db::startTrans();

            $res = (new WithdrawSuccessService())->pass($id);

            Db::commit();

            return success('操作成功', $res);

        } catch (Exception $exception) {
            Db::rollback();
            Log::error($exception->getMessage());
            Log::error($exception->getFile());
            Log::error($exception->getLine());
            return  fail($exception->getMessage());

        }

    }

    /**
     * 已打款
     * @return \think\response\Json
     */
    public function payment()
    {
        //加锁，中间件
        $params = request()->all();

        if ($msg = dmjValidate(['id' => 'require', ], [], $params)) return fail($msg);

        $id = $params['id'] ?? 0;

        try {

            Db::startTrans();

            $res = (new WithdrawSuccessService())->success($id);

            Db::commit();

            return success('操作成功', $res);

        } catch (Exception $exception) {
            Db::rollback();
             Log::error($exception->getMessage());
             Log::error($exception->getFile());
             Log::error($exception->getLine());
            return  fail($exception->getMessage());

        }

    }



}